# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import urllib.request

class DangdangPipeline:
    #itme为管道数据使用pipeline需要再setting中进行开启
    # ITEM_PIPELINES = {
    #     "dangdang.pipelines.DangdangPipeline": 300,
    # }
    def open_spider(self, spider):
        self.fp=open('book.json','w',encoding='utf-8')

    def process_item(self, item, spider):
        self.fp.write(str(item))
        return item
    def close_spider(self, spider):
        self.fp.close()

class DangBookDownloadPipeline:
    def process_item(self, item, spider):
        #注意一定要求看源码图片地址结构
        url=  'https:'+item.get('book_img')
        #需要在核心爬虫文件同目录创建文件夹，并构建图片格式
        filename='./books/'+ item.get('book_name') +'.jpg'
        urllib.request.urlretrieve(url=url,filename=filename)
        return item
